package com.dragonwu.controller;

import com.alibaba.fastjson.JSONObject;
import com.dragonwu.constant.Constants;
import com.dragonwu.model.R;
import com.dragonwu.model.param.LoginParam;
import com.dragonwu.model.vo.LoginVo;
import com.dragonwu.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody LoginParam loginParam) {
        try {
            return R.ok(loginService.login(loginParam), Constants.LOGIN_OK);
        } catch (RuntimeException msg) {
            //返回失败结果
            return R.fail(null, msg.getMessage());
        } catch (Exception e) {
            log.error("后台登录出现异常：" + JSONObject.toJSONString(loginParam), e);
            return R.fail(null, Constants.LOGIN_FAIL);
        }
    }

    @GetMapping("/logout.do")
    public R<String> logout() {
        try {
            loginService.logout();
            return R.ok(null, Constants.LOGOUT_OK);
        } catch (RuntimeException msg) {
            return R.fail(null, msg.getMessage());
        } catch (Exception e) {
            log.error("退出登录出现异常：" + e);
            return R.fail(null, Constants.LOGOUT_FAIL);
        }
    }

    @GetMapping("/captcha")
    public R<Map<String, String>> captcha() {
        try {
            return R.ok(loginService.getCaptcha(), Constants.GET_RESOURCE_OK);
        } catch (RuntimeException msg) {
            return R.fail(null, msg.getMessage());
        } catch (Exception e) {
            log.error("获取验证码出现异常：", e);
            return R.fail(null, Constants.GET_RESOURCE_FAIL);
        }
    }
}
